from collections import defaultdict
import datetime
from apps.menu.models import SysMenu
from apps.user.models import SysUser
from common.auth_jwt import generate_jwt_token
from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
from apps.user.serializers import UserLoginSerializer, SysUserSerializer
from apps.menu.serializers import SysMenuSerializer
from common.authentication import TokenAuthentication
from rest_framework.response import Response



# Create your views here.
class EnterViewSet(ViewSet):
    @action(methods=['get'], detail=False)
    def enter(self, request):
        return Response({"code":200,"msg":"ok"})



class LoginViewSet(ViewSet):
    queryset = SysUser.objects.all()
    serializer_class = UserLoginSerializer
    @action(methods=['POST'], detail=False,authentication_classes=[])
    def pwd(self, request):
        # 获取登录的用户名和密码
        data = request.data
        # 序列化器
        serializer = UserLoginSerializer(data=data)
        # 验证
        serializer.is_valid(raise_exception=True)
        # 获取返回的用户对象
        user = serializer.validated_data['user']
        # 获取用户基本信息
        user_serializer = SysUserSerializer(user)
        # 构造载体数据
        jwt_payload = {
            'user_id':user.id,
            'username':user.username,
            'exp':datetime.datetime.utcnow() + datetime.timedelta(hours=12)
            # 'exp':datetime.datetime.utcnow() + datetime.timedelta(seconds=20)
        }
        # 生成token
        token = generate_jwt_token(jwt_payload)
        # 获取用户的所有角色
        roles = user.user_roles.all()
        # 角色结构
        role_list = [{role.id:role.role.name} for role in roles]  # 提取角色名称

        # 获取用户的所有菜单权限
        menus = []
        for role in roles:
            role_menus = role.role.role_menus.all()
            for role_menu in role_menus:
                menus.append(role_menu.menu)
        menu_data = SysMenuSerializer(menus,many=True).data

        # 进行层级化处理
        hierarchical_menu = build_menu_hierarchy(menu_data)

        # 获取所有的菜单权限
        response_data = {
            'user_id':user.id,
            'username':user.username,
            'user_info':user_serializer.data,
            'token':token,
            'role_list':role_list,
            'menu_list':hierarchical_menu,
        }
        return Response({'data':response_data,'code':200,'msg':"登录成功"})


def build_menu_hierarchy(menu_items):
    """
    将平铺的菜单列表转化为层级结构，并按 order_num 排序。
    :param menu_items: 菜单列表，每个菜单项包含 id, name, parent 等信息
    :return: 层级化的菜单结构
    """
    # 创建一个字典，按父菜单将菜单分组
    menu_dict = defaultdict(list)

    # 将每个菜单项按父菜单分组，并按 order_num 排序
    for menu in menu_items:
        menu_dict[menu['parent']].append(menu)

    # 递归构建层级结构
    def add_children(menu):
        menu['children'] = sorted(menu_dict[menu['id']], key=lambda x: x['order_num'] or 0)  # 按 order_num 排序
        for child in menu['children']:
            add_children(child)  # 递归处理每个子菜单

    # 查找所有根菜单（parent 为 null）
    root_menus = [menu for menu in menu_items if menu['parent'] is None]

    # 对每个根菜单递归添加子菜单
    for menu in root_menus:
        add_children(menu)

    return root_menus

class SetUserInfoViewSet(ViewSet):
    serializer_class = SysUserSerializer
    queryset = SysUser.objects.filter(status=0)
    authentication_classes = []

    def list(self, request):
        queryset = SysUser.objects.filter(status=0)
        serializer = self.serializer_class(queryset, many=True)
        return Response({"code":200,"msg":"list","data":serializer.data})

    def retrieve(self, request, pk=None):
        obj = self.queryset.get(pk=pk)
        serializer = self.serializer_class(obj)
        return Response({"code":200,"msg":"retrieve","data":serializer.data})

    def update(self, request, pk=None):
        obj = self.queryset.get(pk=pk)
        serializer = self.serializer_class(obj, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"code":200,"msg":"update","data":serializer.data})

    def create(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"code":200,"msg":"create","data":serializer.data})

    def delete(self, request, pk=None):
        obj = self.queryset.get(id=pk)
        obj.status=1
        obj.save()
        return Response({"code":200,"msg":"delete success"})


    @action(methods=['POST'], detail=False, authentication_classes=[TokenAuthentication])
    def set_avatar(self, request):
        user = request.user.user_object
        avatar = request.FILES.get('avatar')
        if not avatar:
            return Response({"code": 400, "msg": "头像文件未提供"})
        # 设置新的头像
        user.avatar = avatar
        user.save()
        serializer = SysUserSerializer(user)
        return Response({"code":200,"msg":"头像修改成功","data":serializer.data})

    @action(methods=['patch'], detail=False, authentication_classes=[TokenAuthentication])
    def update_user_info(self, request):
        user = request.user.user_object
        data = request.data
        serializer = SysUserSerializer(user, data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({'code':200,'msg':'update success!','data':serializer.data})

    @action(methods=['patch'], detail=False, authentication_classes=[TokenAuthentication])
    def change_password(self, request):
        user = request.user.user_object
        data = request.data
        old_password = data['oldPassword']
        if not user.check_password(old_password):
            return Response({"code":400,"msg":"旧密码错误，请重试！"})
        new_password = data['newPassword']
        user.set_password(new_password)
        user.save()
        return Response({'code':200,'msg':'修改成功'})
